(function($, doc){
	var masterpage = {
		/**
		 * config	:
		 * 		tmp : '',
		 * 		placeholderMap : {},
		 * 		data : {},
		 * 		callback : function
		 */
		apply : function(config){
			config = $.extend(true, {}, {
			    pageID : 'pageID',
                pageTitle : '',
                tmp : this.defaultTmp,
                placeholderMap : {
                    mainPlaceholder : '.mainPlaceholderContent'
                }
            }, config );
			var $masterpageHtml = $( tmpl( config['tmp'], config ) ).appendTo( doc.body );
			$.each( config['placeholderMap'], function(placeholderID, placeholderSelector ){				
				$( '#' + placeholderID, $masterpageHtml ).append( $(placeholderSelector) );
			});
			if( config['callback'] ){
				config['callback'].call( $masterpageHtml );
			}
		}, 
		/**
		 * 默认页面母板. 
		 */
		defaultTmp : [
            '<div class="wrap">',
                '<div class="content">',
                    '<div class="subheader" id="<%=o.pageID%>" >',
                        '<h2>',
                            '<%= String.isExpression(o.pageTitle) ? o.pageTitle.evaluate() : o.pageTitle %>',
                        '</h2>',
                    '</div>',
                    '<div id="mainPlaceholder"></div>',
                '</div>',
            '</div>',
        ].join(''), 
        /**
         * 解析页面模板.
         * 页面加载后默认执行. 
         */
        parse : function(){
            var body = doc.body,
                isApplyMasterPage = body.hasAttribute('masterpage');
                
            if(isApplyMasterPage){
                var masterpageTmp = body.getAttribute('masterpage');
                if(!masterpageTmp || masterpageTmp == 'default'){
                    masterpageTmp =  this.defaultTmp;
                }
                masterpage.apply({        
                    tmp : masterpageTmp,
                    pageID : body.getAttribute('pageID'),
                    pageTitle : body.getAttribute('pageTitle')
                });
            }
        }
	};
	
	//-----------------------------------------------------------------------------------------
	
	ujs.define('masterpage', 'ujs.browser', function(){
        return masterpage;
    });
	
	$(function(){    
        ujs.browser.masterpage.parse();    
    });
})($, document);